﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using DWH.Utils;
using DWH.Data;
using DWH.Configuration;
using DWH.PP.LoopUrls;

namespace DWH.PP.Push
{
    public class PageAttachmentFromPageContentPushTask : PPTaskBase
    {
        protected string TargetPullTaskName;
        protected string TargetPullTaskAssemblyFile;
        protected string TargetPullTaskTypeName;
        protected int MaxTryPushRound;

        private ILog logger;

        public override void Initialize()
        {
            logger = LogManager.GetLogger(typeof(PageAttachmentFromPageContentPushTask));

            InitializeTaskInfoFromDB();

            TargetPullTaskName = ExtendData[DWHConstants.KEY_PUSH_TARGET_PULL_TASK_NAME];
            TargetPullTaskAssemblyFile = ExtendData[DWHConstants.KEY_PUSH_TARGET_PULL_TASK_ASSEMBLY_FILE];
            TargetPullTaskTypeName = ExtendData[DWHConstants.KEY_PUSH_TARGET_PULL_TASK_TYPE_NAME];

            MaxTryPushRound = Int32.Parse(ExtendData[DWHConstants.KEY_PUSH_MAX_TRY_ROUND]);
        }

        public override void Run()
        {
            RDTaskConfiguration config = new RDTaskConfiguration();
            config.Enable = true;
            config.TaskName = TargetPullTaskName;
            config.AssemblyFile = TargetPullTaskAssemblyFile;
            config.TypeName = TargetPullTaskTypeName;

            foreach (KeyValuePair<string, string> data in ExtendData)
            {
                if (!config.ExtendData.ContainsKey(data.Key))
                {
                    config.ExtendData.Add(data.Key,data.Value);
                }
            }

            PPLoopUrlsBoardPullTask processTask = (PPLoopUrlsBoardPullTask)PPTaskExecutor.CreatePPTaskFromRDTaskConfiguration(config);
            
            for (int i = 0; i < MaxTryPushRound; i++)
            {
                Dictionary<long, Page> pages = DWHDBHelper.GetPageContentForPush(TaskName, TargetPullTaskName, 100);

                foreach (KeyValuePair<long,Page> p in pages)
                {
                    processTask.ProcessTargetHtmlContent(p.Value.PageUrl, p.Value.PageContent);

                    DWHDBHelper.AddPushHistory(TaskName, p.Key, DateTime.Now);
                }
            }
        }

        public override void Reset()
        {

        }
    }
}
